<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * Newsletter class
 *
 * @category	Admin
 */
class NewsletterAction extends AdminAction
{


    protected $Newsletter;
    protected $Queue;


    //初始化
	public function _initialize()
	{
		parent::_initialize();
		$this->Newsletter = M('Newsletter');
		$this->Queue = M('NewsletterQueue');
	}


	/**
	 * @desc 队列项目列表
	 *
	 */
	public function newsletterQueue()
	{
	    import('ORG.Util.Page');

	    $map = array();
	    $newsletter = array();
		$parameter = '';
		if (isset($_GET['letter_id']))
		{
			$map['letter_id'] = $_GET['letter_id'];
			$paramter .= 'letter_id='.$_GET['letter_id'].'&';
			$newsletter = $this->Newsletter->find($_GET['letter_id']);
		}

    	$total = $this->Queue->where($map)->count();
    	$Page  = new Page($total);
    	$Page->parameter = $parameter;
		$pagination = $Page->show();
    	$list = $this->Queue->where($map)->limit($Page->firstRow.','.$Page->listRows)->select();

    	$this->assign('newsletter', $newsletter);
    	$this->assign('list', $list);
    	$this->assign('pagination', $pagination);
    	$this->display();
	}


	/**
	 * @desc 发送newsletter
	 *
	 */
	public function sendNewsletter()
	{
	    $letterID = intval($_GET['letter_id']);
		$start = intval($_GET['start']);

		$map = array('letter_id' => $letterID);
        $order = array('priority' => 'asc', 'queue_id' => 'asc');

		if (empty($start))
		{
			$item = $this->Queue->where($map)->order($order)->find();
		}
		else
		{
			$map['queue_id'] = array('gt', $start);
			$item = $this->Queue->where($map)->order($order)->find();
		}

		if (!empty($item))
		{
			$newsletter = $this->Newsletter->find($item['letter_id']);

			$to = $item['email'];
			$subject = ubb2html($newsletter['subject']);
			$message = ubb2html($newsletter['message']);
            $userID = $item['user_id'];

			$Mailer = A('Mailer');
			$result = $Mailer->newsletter($to, $subject, $message, $userID);

			$recipient = htmlspecialchars($to);
			$map  = array('queue_id' => $item['queue_id']);

			if (!$result)
			{
				$data = array(
				    'last_send_time' => time(),
				    'failed_count'   => array('exp', 'failed_count+1'),
				);
				$this->Queue->where($map)->save($data);
				$message = sprintf(L('newsletter.send_failed'), $recipient, $result);
			}
			else
			{
				$this->Queue->where($map)->delete();
				$message = sprintf(L('newsletter.send_succeed'), $recipient);
			}

			$start  = $item['queue_id'];
			$jumUrl = __ACTION__.'/letter_id/'.$letterID.'/start/'.$start;

			$this->assign('jumpUrl', $jumUrl);
			$this->assign('loader', TRUE);
			$this->success($message);
		}
		else
		{
			//删除错误超过两次的记录
			$map = array(
			    'letter_id' => $letterID,
			    'failed_count' => array('gt', 2),
			);
			$this->Queue->where($map)->delete();

			$map  = array('letter_id' => $letterID);
			$this->Newsletter->where($map)->setField('last_send_time', time());

			$this->assign('jumpUrl', __URL__.'/newsletterList');
			$this->assign('waitSecond', 86400);
			$this->success(L('newsletter.task_completed'));
		}
	}


	/**
	 * @desc 删除队列项目
	 *
	 */
	public  function removeTargetUser()
	{
	    if (empty($_POST['mods']))
	    {
	        $this->error('newsletter.no_target_user_selected');
	    }
	    if ($this->isPost())
	    {
	       $map = array('queue_id' => array('in', $_POST['mods']));
	       $this->Queue->where($map)->delete();
		   $this->success(L('newsletter.target_user_removed_succeed'));
	    }
	}


	/**
	 * @desc newsletter列表
	 *
	 */
	public function newsletterList()
	{
		import('ORG.Util.Page');

        $User = M('User');

		$order = array('letter_id' => 'desc');
    	$total = $this->Newsletter->count();
    	$Page  = new Page($total);
		$pagination = $Page->show();
    	$results = $this->Newsletter->order($order)->limit($Page->firstRow.','.$Page->listRows)->select();

    	$newsletterList = array();
    	if (!empty($results))
    	{
    	   foreach ($results as $value)
    	   {
    	       //未投递数
    	       $map = array('letter_id' => $value['letter_id']);
               $unsendCount = $this->Queue->where($where)->count();
    	       $value['target_group'] = !empty($value['target_group']) ? explode(',', $value['target_group']) : array();
    	       $value['unsend_count'] = $unsendCount;
    	       $newsletterList[] = $value;
    	   }
    	}

    	$this->assign('newsletterList', $newsletterList);
    	$this->assign('pagination', $pagination);
    	$this->display();
	}


	/**
	 * @desc 增加newsletter
	 *
	 */
	public function addNewsletter()
	{
		$this->editNewsletter();
	}


	/**
	 * @desc 编辑newsletter
	 *
	 */
	public function editNewsletter()
	{

		$letterID = isset($_REQUEST['letter_id']) ? intval($_REQUEST['letter_id']) : 0;
		$priority = intval($_POST['priority']);
		$newTargetGroups = implode(',', $_POST['target_group']);
		$result = $this->Newsletter->find($letterID);

		if ($this->isPost())
		{
			$originalGroups = !empty($result) ? $result['target_group'] : '';
			$targetGroups = !empty($newTargetGroups) ? $originalGroups.','.$newTargetGroups : $originalGroups;
			$targetGroups = trim($targetGroups, ',');
			$data = array(
				'subject'       => $_POST['subject'],
				'message'       => $_POST['message'],
				'author'        => $this->_admin['username'],
				'target_group'  => $targetGroups,
				'priority'      => intval($_POST['priority']),
			);
			if (empty($result))
			{
			    $data['create_time'] = time();
				$letterID = $this->Newsletter->add($data);
			}
			else
			{
			    $data['edit_time'] = time();
				$map = array('letter_id' => $letterID);
				$this->Newsletter->where($map)->save($data);
			}

			if (empty($newTargetGroups))
			{
				$this->success(L('newsletter.newsletter_updated_succeed'));
			}
			else
			{
				$options = array(
					'start' => 0,
					'letter_id' => $letterID,
					'groups' => $newTargetGroups,
					'priority' => $priority,
				);
				$this->redirect('Admin-Newsletter/joinNewsletterQueue', $options);
			}
		}
		else
		{
			$UserGroup = M('UserGroup');
			$field = array('group_id','name');
			$userGroupList = $UserGroup->field($field)->select();
			$this->assign('userGroupList', $userGroupList);

			$priorityOptions = array(
			    3 => L('newsletter.priority_low'),
			    2 => L('newsletter.priority_normal'),
			    1 => L('newsletter.priority_high'),
			);
			$this->assign('priorityOptions', $priorityOptions);
			$this->assign('prioritySelected', $result['priority']);

			$this->assign('rs', $result);
			$this->display('editNewsletter');
		}
	}


    /**
     * @desc 移除目标用户组
     *
     */
	public function removeTargetGroup()
	{
	    $letterID = intval($_GET['letter_id']);
	    $groupID = intval($_GET['group_id']);


	    $prefix = C('DB_PREFIX');

	    $sql = "DELETE FROM {$prefix}newsletter_queue WHERE letter_id='{$letterID}' AND user_id IN (SELECT user_id FROM {$prefix}user WHERE user_group='{$groupID}')";
	    $this->Newsletter->query($sql);

	    $result = $this->Newsletter->find($letterID);
	    $targetGroups = explode(',', $result['target_group']);
	    foreach ($targetGroups as $key => $value)
	    {
	    	if ($groupID == $value)
	    	{
	    		unset($targetGroups[$key]);
	    	}
	    }
	    $this->Newsletter->where('letter_id='.$letterID)->setField('target_group', implode(',', $targetGroups));
	    $this->redirect('Admin-Newsletter/newsletterList');
	}


	/**
	 * @desc 删除newletter
	 *
	 */
	public function deleteNewsletter()
	{


		$letterID = intval($_REQUEST['letter_id']);

		$map = array('letter_id' => $letterID);
		$this->Queue->where($map)->delete();

		$map = array('letter_id' => $letterID);
		$this->Newsletter->where($map)->delete();
		$this->success(L('newsletter.newsletter_deleted_succeed'));
	}


	/**
	 * @desc 插入newletter发送队列
	 *
	 */
	public function joinNewsletterQueue()
	{
		$limit = 100;
		$targetGroups = $_REQUEST['groups'];
		$letterID = intval($_REQUEST['letter_id']);
		$priority = intval($_REQUEST['priority']);
		$start = isset($_REQUEST['start']) ? intval($_REQUEST['start']) : 0;

		$map   = array('user_group' => array('in', $targetGroups));
		$field = array('user_id','username','email');


		$users = $this->_User->field($field)->where($map)->limit($start.','.$limit)->select();
		if (!empty($users)) {
			foreach ($users as $value) {
				$list[] = array(
				    'letter_id' => $letterID,
					'user_id'   => $value['user_id'],
					'username'  => $value['username'],
					'email'     => $value['email'],
					'priority'  => $priority,
				);
			}
			$this->Queue->addAll($list);
		}

		$count = count($users);
		if ($count < $limit)
		{
			$this->assign('jumpUrl', __URL__.'/newsletterList');
			if ($count > 0)
			{
				$userCount = $this->_User->where($map)->count();
				$message = sprintf(L('newsletter.queue_updated_succeed'), $userCount);
			}
			else
			{
				$message = L('newsletter.newsletter_updated_succeed');
			}
			$this->success($message);
		}
		else
		{
			$start = $start + $limit;
			$jumpUrl  = __URL__.'/joinNewsletterQueue';
			$jumpUrl .= '/start/'.$start;
			$jumpUrl .= '/letter_id/'.$letterID;
			$jumpUrl .= '/groups/'.$targetGroups;
			$jumpUrl .= '/priority/'.$Priority;
			$this->assign('jumpUrl', $jumpUrl);
			$this->assign('loader', true);
			$this->success("Be patient, adding users to newsletter queue ...");
		}
	}

}
// End  Class

/* End of file NewsletterAction.class.php */
/* Location: ./App/Lib/Action/Admin/NewsletterAction.class.php */